var ds;
function displayCommContent() {
	Ext.form.Field.prototype.msgTarget = 'side';
	Ext.QuickTips.init();
	var sm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});
	ds = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.JsonReader({
			root : 'entrances',
			id : 'id',
			fields : [ {
				name : 'id'
			}, {
				name : 'name'
			}, {
				name : 'url'
			}, {
				name : 'creator'
			}, {
				name : 'createTime'
			}, {
				name : 'subtype'
			}, {
				name : 'targetType'
			}, {
				name : 'tags'
			}, {
				name : 'status'
			}, {
				name : 'sites'
			}
			// {name: 'description'}
			]
		})
	});
	var gridCm = new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), {
		header : TXT_entrance_name,
		dataIndex : 'name',
		width : 100
	}, {
		header : TXT_entrance_url,
		dataIndex : 'url',
		width : 125
	}, {
		header : TXT_creator,
		dataIndex : 'creator',
		width : 100
	}, {
		header : TXT_createTime,
		dataIndex : 'createTime',
		width : 75
	}, {
		header : TXT_entrance_subtype,
		dataIndex : 'subtype',
		width : 75
	}, {
		header : TXT_entrance_targetType,
		dataIndex : 'targetType',
		width : 90
	}, {
		header : TXT_entrance_tags,
		dataIndex : 'tags',
		width : 175
	}, {
		header : TXT_entrance_status,
		dataIndex : 'status',
		width : 45,
		renderer : function(value) {
			if (value == 0)
				return '<span style="color:red;">未生效</span>';
			else if (value == 1)
				return '<span style="color:green;">已生效</span>';
		}
	}, {
		header : TXT_entrance_sites,
		dataIndex : 'sites',
		width : 135
	}
	// {header:TXT_entrance_description,dataIndex:'description',width:200}
	]);
	var btnCreate = new Ext.Button({
		text : TXT_common_create,
		tooltip : TXT_common_create,
		iconCls : 'icoAdd'
	});

	var btnEdit = new Ext.Button({
		text : TXT_common_edit,
		tooltip : TXT_common_edit,
		iconCls : 'icoDetail'
	});

	var btnDelete = new Ext.Button({
		text : TXT_common_delete,
		tooltip : TXT_common_delete,
		iconCls : 'icoDel'
	});

	btnCreate.on('click', function() {
		createEntranceFormWin('');
	});

	btnEdit.on('click', function() {
		if (sm.getCount() == 0) {
			Ext.MessageBox.alert(TXT_common_hint, TXT_user_need);
			return;
		}
		var record = sm.getSelected();
		createEntranceFormWin(record.id);
	});
	btnDelete
			.on(
					'click',
					function() {
						if (sm.getCount() == 0) {
							Ext.MessageBox
									.alert(TXT_common_hint, TXT_user_need);
							return;
						}
						var record = sm.getSelected();
						Ext.MessageBox
								.confirm(
										TXT_common_hint,
										TXT_user_delete_confirmation,
										function(btn) {
											if (btn == 'yes') {
												BestvSearch.showWaitingWin();
												Ext.Ajax
														.request({
															url : DISPATCH_URL,
															method : 'POST',
															params : 'cmd=entrance&action=delete&id='
																	+ record.id,
															success : function(
																	response,
																	options) {
																Ext.MessageBox
																		.hide();
																var s = response.responseText;
																if (s == '[error]') {
																	Ext.MessageBox
																			.alert(
																					TXT_common_hint,
																					TXT_common_access_fail);
																} else if (s == '[null]') {
																	Ext.MessageBox
																			.alert(
																					TXT_common_hint,
																					TXT_common_relogin,
																					function() {
																						window.location.href = LOGIN_URL;
																					});
																} else {
																	var result = Ext.util.JSON
																			.decode(s);
																	if (result.result == 'success') {
																		reloadEntranceDs();
																	}
																}
															},
															failure : function(
																	response,
																	options) {
																Ext.MessageBox
																		.hide();
																Ext.MessageBox
																		.alert(
																				TXT_common_hint,
																				TXT_common_access_fail);
															}
														});
											}
										});
					});
	var grid = new Ext.grid.GridPanel({
		el : 'grid',
		ds : ds,
		cm : gridCm,
		sm : sm,
		stripeRows : true,
		loadMask : true,
		title : TXT_comm_title,
		tbar : [ btnCreate, '-', btnEdit, '-', btnDelete ]
	});
	ds.baseParams = {
		cmd : 'entrance',
		action : 'findComm',
		'typename' : '商品'
	};
	ds.on('load', function() {
		grid.getSelectionModel().selectFirstRow();
	});
	ds.load();

	BestvSearch.glb_mainPanel.add(grid);
	BestvSearch.drawMainFrame(TXT_app_name + ' - ' + TXT_comm_title);
}

function reloadEntranceDs() {
	ds.reload();
}

Ext.onReady(displayCommContent);

function createEntranceFormWin(entranceId) {
	var eid = entranceId;
	var siteDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.JsonReader({
			root : 'sites',
			id : 'id',
			fields : [ {
				name : 'id'
			}, {
				name : 'name'
			}, {
				name : 'code'
			} ]
		})
	});
	siteDs.baseParams = {
		cmd : 'site',
		action : 'findExpHDQ'
	};

	var siteSm = new Ext.grid.CheckboxSelectionModel();
	var siteCm = new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), siteSm,
			{
				header : TXT_site_name,
				dataIndex : 'name',
				width : 200
			}, {
				header : TXT_site_code,
				dataIndex : 'code',
				width : 200
			} ]);

	var siteGrid = new Ext.grid.GridPanel({
		border : true,
		region : 'center',
		ds : siteDs,
		cm : siteCm,
		sm : siteSm,
		stripeRows : true,
		loadMask : true,
		title : TXT_entrance_site
	});
	siteDs.load();
	// target type combox
	var targetTypeDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.JsonReader({
			root : 'targetTypes',
			id : 'id',
			fields : [ {
				name : 'id'
			}, {
				name : 'name'
			} ]
		})
	});
	targetTypeDs.baseParams = {
		'cmd' : 'targetType',
		'action' : 'find'
	};
	var targetTypeCombo = new Ext.form.ComboBox({
		// tpl: '<tpl for="."><div ext:qtip="{bic}. {name}"
		// class="x-combo-list-item">{bic}</div></tpl>',
		fieldLabel : TXT_entrance_targetType,
		id : 'entranceTargetType',
		name : 'entranceTargetType',
		displayField : 'name',
		emptyText : '选择目标类型...',
		valueField : 'id',
		typeAhead : true,
		triggerAction : 'all',
		selectOnFocus : true,
		triggerClass : 'x-form-trigger2',
		store : targetTypeDs,
		lazyInit : false,
		editable : false,
		allowBlank : true
	});
	targetTypeDs.on('load', function() {
		targetTypeCombo.setValue(targetTypeCombo.getValue());
	});
	targetTypeDs.load();
	// sub type combo
	var subTypeDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.JsonReader({
			root : 'subTypes',
			id : 'id',
			fields : [ {
				name : 'id'
			}, {
				name : 'name'
			} ]
		})
	});
	subTypeDs.baseParams = {
		'cmd' : 'subType',
		'action' : 'findComm',
		'typename' : '商品'
	};
	subTypeDs.on('loadexception', function() {
	});
	var subTypeCombo = new Ext.form.ComboBox({
		fieldLabel : TXT_entrance_subtype,
		id : 'entranceSubType',
		name : 'entranceSubType',
		displayField : 'name',
		emptyText : '选择子类型',
		valueField : 'id',
		typeAhead : true,
		triggerAction : 'all',
		selectOnFocus : true,
		triggerClass : 'x-form-trigger2',
		store : subTypeDs,
		lazyInit : false,
		editable : true,
		allowBlank : true
	});
	subTypeDs.on('load', function() {
		if (subTypeDs.getCount() == 1) {
			subTypeCombo.setValue(subTypeDs.getAt(0).get('id'));
			subTypeCombo.setDisabled(true);
		}
	});
	subTypeDs.load();
	var entranceForm = new Ext.FormPanel({
		labelAlign : 'right',
		region : 'north',
		labelWidth : 75,
		height : 150,
		frame : true,
		items : [ {
			layout : 'column',
			items : [
					{
						columnWidth : .5,
						layout : 'form',
						defaultType : 'textfield',
						defaults : {
							anchor : '85%'
						},
						items : [ {
							fieldLabel : TXT_entrance_name,
							id : 'entranceName',
							name : 'entranceName',
							allowBlank : false
						}, {
							fieldLabel : TXT_entrance_url,
							id : 'entranceUrl',
							name : 'entranceUrl',
							allowBlank : false
						}, new Ext.form.DateField({
							fieldLabel : TXT_entrance_valid_date,
							id : 'validDate',
							name : 'validDate',
							format : 'Y-m-d',
							allowBlank : false
						}), new Ext.form.DateField({
							fieldLabel : TXT_entrance_invalid_date,
							id : 'invalidDate',
							name : 'invalidDate',
							format : "Y-m-d",
							allowBlank : false
						}), {
							fieldLabel : TXT_entrance_tags,
							id : 'tags',
							name : 'tags',
							emptyText : 'tag之间请用空格隔开...',
							allowBlank : true
						} ]
					},
					{
						columnWidth : .5,
						layout : 'form',
						defaultType : 'textfield',
						defaults : {
							anchor : '85%'
						},
						items : [ targetTypeCombo, subTypeCombo,
								new Ext.form.TimeField({
									fieldLabel : TXT_entrance_valid_time,
									id : 'validTime',
									name : 'validTime',
									editable : false,
									format : "G:i"
								}), new Ext.form.TimeField({
									fieldLabel : TXT_entrance_invalid_time,
									id : 'invalidTime',
									name : 'invalidTime',
									editable : false,
									format : "G:i"
								}), {
									fieldLabel : TXT_entrance_description,
									id : 'description',
									name : 'description',
									allowBlank : true
								} ]
					} ]
		} ]
	});
	var win = null;
	if (!win) {
		win = new Ext.Window(
				{
					title : TXT_comm_title,
					width : 600,
					height : 400,
					autoScroll : false,
					layout : 'border',
					border : false,
					minimizable : false,
					maximizable : false,
					resizable : false,
					modal : true,
					layoutConfig : {
						animate : false
					},
					items : [ entranceForm, siteGrid ],
					buttonAlign : 'center',
					buttons : [
							{
								text : TXT_common_OK,
								handler : function() {
									if (!entranceForm.form.isValid())
										return;
									var entranceName = entranceForm.findById(
											'entranceName').getValue();
									var entranceUrl = entranceForm.findById(
											'entranceUrl').getValue();
									var validDate = Ext.util.Format.date(
											entranceForm.findById('validDate')
													.getValue(), 'Y-m-d');
									var validTime = entranceForm.findById(
											'validTime').getValue();
									var invalidDate = Ext.util.Format.date(
											entranceForm
													.findById('invalidDate')
													.getValue(), 'Y-m-d');
									var invalidTime = entranceForm.findById(
											'invalidTime').getValue();
									var tags = entranceForm.findById('tags')
											.getValue();
									var targetType = entranceForm.findById(
											'entranceTargetType').getValue();
									var subType = entranceForm.findById(
											'entranceSubType').getValue();
									var description = entranceForm.findById(
											'description').getValue();

									var siteCodes = "";
									var siteRecord = siteSm.getSelections();
									for ( var i = 0; i < siteRecord.length; ++i) {
										siteCodes += "&siteCode="
												+ siteRecord[i].get("code");
									}
									BestvSearch.showWaitingWin();
									Ext.Ajax
											.request({
												url : DISPATCH_URL,
												method : 'post',
												params : 'cmd=entrance&action=save&id='
														+ eid
														+ '&name='
														+ entranceName
														+ '&url='
														+ entranceUrl
														+ '&vdate='
														+ validDate
														+ '&vtime='
														+ validTime
														+ '&invdate='
														+ invalidDate
														+ '&invtime='
														+ invalidTime
														+ '&tags='
														+ tags
														+ '&target='
														+ targetType
														+ '&subtype='
														+ subType
														+ '&description='
														+ description
														+ siteCodes,
												success : function(response,
														options) {
													Ext.MessageBox.hide();
													var s = response.responseText;
													if (s == 'error') {
														Ext.MessageBox
																.alert(
																		TXT_common_hint,
																		TXT_common_access_fail);
													} else if (s == 'null') {
														Ext.MessageBox
																.alert(
																		TXT_common_hint,
																		TXT_common_relogin,
																		function() {
																			window.location.href = '../eni/common/logout.jsp';
																		});
													} else {
														var result = Ext.util.JSON
																.decode(s);
														if (result.result == 'success') {
															win.close();
															reloadEntranceDs();
														} else {
															Ext.MessageBox
																	.alert(
																			TXT_common_hint,
																			result.message);
														}
													}
												},
												failure : function(respond,
														options) {
													Ext.MessageBox.hide();
													Ext.MessageBox
															.alert(
																	TXT_common_hint,
																	TXT_common_access_fail);
												}

											});
								}
							}, {
								text : TXT_common_cancel,
								handler : function() {
									win.close();
								}
							} ]
				});
	}
	win.on('show', function() {
		if (eid != '') {
			Ext.Ajax.request({
				url : DISPATCH_URL,
				method : 'post',
				params : 'cmd=entrance&action=get&id=' + eid,
				success : function(response, options) {
					var s = response.responseText;
					if (s == '[error]')
						Ext.MessageBox.alert(TXT_common_hint,
								TXT_common_access_fail);
					else if (s == '[null]') {
						Ext.MessageBox.alert(TXT_common_hint,
								TXT_common_relogin, function() {
									window.location.href = LOGIN_URL;
								});
					} else {
						var result = Ext.util.JSON.decode(s);
						entranceForm.findById('entranceName').setValue(
								result.name);
						entranceForm.findById('entranceUrl').setValue(
								result.url);
						entranceForm.findById('validDate').setValue(
								result.startDate);
						entranceForm.findById('validTime').setValue(
								result.startTime);
						entranceForm.findById('invalidDate').setValue(
								result.endDate);
						entranceForm.findById('invalidTime').setValue(
								result.endTime);
						entranceForm.findById('tags').setValue(result.tags);
						entranceForm.findById('entranceTargetType').setValue(
								result.targetType);
						entranceForm.findById('entranceSubType').setValue(
								result.subType);
						description = entranceForm.findById('description')
								.setValue(result.description);
					}
				},
				failure : function(response, options) {
					Ext.MessageBox.alert(TXT_common_hint,
							TXT_common_access_fail);
				}
			});
		}

	});
	win.show();
	siteDs.on('load', function() {
		if (eid != '') {
			Ext.Ajax.request({
				url : DISPATCH_URL,
				method : 'post',
				params : 'cmd=entrance&action=getEntranceSiteIds&id=' + eid,
				success : function(response, options) {
					var s = response.responseText;
					if (s == '[error]')
						Ext.MessageBox.alert(TXT_common_hint,
								TXT_common_access_fail);
					else if (s == '[null]') {
						Ext.MessageBox.alert(TXT_common_hint,
								TXT_common_relogin, function() {
									window.location.href = LOGIN_URL;
								});
					} else {
						var result = Ext.util.JSON.decode(s);
						var arr = result.siteIds.split(' ');

						var siteRecords = siteDs.reader.jsonData;
						for ( var i = 0; i < siteRecords.sites.length; i++) {
							var record = siteRecords.sites[i];
							for ( var j = 0; j < arr.length; j++) {
								if (arr[j] == record.id) {
									siteSm.selectRow(i, true);
								}
							}
						}
					}
				},
				failure : function(response, options) {
					Ext.MessageBox.alert(TXT_common_hint,
							TXT_common_access_fail);
				}
			});
		}
		if (siteDs.getCount() == 1)
			siteSm.selectFirstRow();
	});

}